package com.newshub.app.ui.news

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.View
import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.lifecycle.ViewModelProvider
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.newshub.app.R
import com.newshub.app.data.model.News

class NewsDetailActivity : AppCompatActivity() {
    
    private lateinit var toolbar: Toolbar
    private lateinit var progressBar: ProgressBar
    private lateinit var titleTextView: TextView
    private lateinit var sourceTextView: TextView
    private lateinit var timeTextView: TextView
    private lateinit var imageView: ImageView
    private lateinit var contentTextView: TextView
    private lateinit var errorTextView: TextView
    private lateinit var favoriteButton: FloatingActionButton
    
    private lateinit var viewModel: NewsDetailViewModel
    private var newsId: String = ""
    private var isFavorite: Boolean = false
    private val handler = Handler(Looper.getMainLooper())
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        // 添加详细的日志记录
        Log.d("NewsDetailActivity", "onCreate开始执行")
        Log.d("NewsDetailActivity", "应用包名: ${packageName}")
        Log.d("NewsDetailActivity", "Intent: ${intent}")
        
        try {
            // 简化布局，避免复杂的渲染问题
            Log.d("NewsDetailActivity", "设置布局文件")
            setContentView(R.layout.activity_news_detail)
            
            // 获取新闻ID
            newsId = intent.getStringExtra("news_id") ?: ""
            Log.d("NewsDetailActivity", "获取到的新闻ID: ${newsId}")
            
            if (newsId.isEmpty()) {
                showErrorAndFinish("新闻ID无效")
                return
            }
            
            // 最小化初始化流程，先只初始化必要的视图
            initCriticalViews()
            
            // 立即初始化所有必要组件，不使用延迟加载以避免潜在问题
            initViews() // 先初始化所有视图
            setupToolbar() // 然后设置工具栏
            initViewModel() // 接着初始化ViewModel
            setupFavoriteButton() // 最后设置收藏按钮
            
            // 直接加载新闻详情
            loadNewsDetail()
        } catch (e: Exception) {
            Log.e("NewsDetailActivity", "onCreate失败", e)
            // 如果发生异常，直接显示Toast然后退出
            Toast.makeText(this, "应用启动失败: ${e.message}", Toast.LENGTH_SHORT).show()
            finish()
        }
    }
    
    private fun initCriticalViews() {
        // 只初始化必要的视图
        progressBar = findViewById(R.id.progressBar)
        errorTextView = findViewById(R.id.errorTextView)
    }
    
    private fun initViews() {
        // 初始化所有视图
        toolbar = findViewById(R.id.toolbar)
        titleTextView = findViewById(R.id.titleTextView)
        sourceTextView = findViewById(R.id.sourceTextView)
        timeTextView = findViewById(R.id.timeTextView)
        // imageView在布局文件中被注释掉了，暂时注释掉这行
        // imageView = findViewById(R.id.imageView)
        contentTextView = findViewById(R.id.contentTextView)
        favoriteButton = findViewById(R.id.favoriteButton)
        
        // 确保imageView被禁用，避免任何形式的渲染
        // imageView.visibility = View.GONE
    }
    
    private fun initViewModel() {
        try {
            viewModel = ViewModelProvider(this)[NewsDetailViewModel::class.java]
            
            // 观察新闻详情
            viewModel.newsDetail.observe(this) { news ->
                try {
                    hideLoading()
                    if (news != null) {
                        if (news.title.isNullOrEmpty()) {
                            showError("新闻标题为空")
                        } else {
                            showNewsDetail(news)
                        }
                    } else {
                        showError("新闻详情加载失败")
                    }
                } catch (e: Exception) {
                    Log.e("NewsDetailActivity", "观察新闻详情失败", e)
                    showError("显示新闻详情失败")
                }
            }
            
            // 观察加载状态
            viewModel.isLoading.observe(this) { isLoading ->
                try {
                    if (isLoading) {
                        showLoading()
                    } else {
                        hideLoading()
                    }
                } catch (e: Exception) {
                    Log.e("NewsDetailActivity", "观察加载状态失败", e)
                }
            }
            
            // 观察错误信息
            viewModel.errorMessage.observe(this) { errorMessage ->
                try {
                    if (errorMessage != null) {
                        showError(errorMessage)
                    }
                } catch (e: Exception) {
                    Log.e("NewsDetailActivity", "观察错误信息失败", e)
                }
            }
        } catch (e: Exception) {
            Log.e("NewsDetailActivity", "初始化ViewModel失败", e)
            throw e // 重新抛出以便上层处理
        }
    }
    
    private fun setupToolbar() {
        try {
            // 禁用窗口默认的ActionBar，以便使用自定义Toolbar
            setSupportActionBar(toolbar)
            supportActionBar?.setDisplayHomeAsUpEnabled(true)
            supportActionBar?.setDisplayShowHomeEnabled(true)
            toolbar.setNavigationOnClickListener {
                finish()
            }
        } catch (e: Exception) {
            Log.e("NewsDetailActivity", "设置工具栏失败", e)
            // 如果设置工具栏失败，我们可以直接在toolbar上设置一个返回按钮
            try {
                toolbar.navigationIcon = resources.getDrawable(android.R.drawable.ic_menu_close_clear_cancel, theme)
                toolbar.setNavigationOnClickListener {
                    finish()
                }
            } catch (innerE: Exception) {
                Log.e("NewsDetailActivity", "设置返回按钮失败", innerE)
            }
        }
    }
    
    private fun setupFavoriteButton() {
        try {
            // favoriteButton是lateinit属性，不需要安全调用
            favoriteButton.setOnClickListener {
                toggleFavorite()
            }
        } catch (e: Exception) {
            Log.e("NewsDetailActivity", "设置收藏按钮失败", e)
        }
    }
    
    private fun loadNewsDetail() {
        showLoading()
        viewModel.loadNewsDetail(newsId)
    }
    
    private fun showNewsDetail(news: News) {
        try {
            // 避免空指针异常
            titleTextView.text = news.title ?: "无标题"
            sourceTextView.text = news.source ?: "未知来源"
            timeTextView.text = news.ptime ?: "未知时间"
            
            // 获取新闻详情内容
            try {
                // 先显示摘要内容
                val digest = news.digest ?: "暂无内容摘要"
                contentTextView.text = digest
                
                        // 异步获取详细内容
                        Thread {
                            try {
                                val repository = com.newshub.app.data.repository.NewsRepository
                                val newsDetail = repository.getNewsDetailSync(news.docid)
                        if (newsDetail != null && newsDetail.body.isNotBlank()) {
                            // 在主线程更新UI
                            runOnUiThread {
                                contentTextView.text = newsDetail.body
                                Log.d("NewsDetailActivity", "成功加载详细内容")
                            }
                        } else {
                            Log.d("NewsDetailActivity", "新闻详情为空，保持显示摘要")
                        }
                    } catch (e: Exception) {
                        Log.e("NewsDetailActivity", "获取新闻详情内容失败", e)
                        // 如果获取详情失败，保持显示摘要内容
                        runOnUiThread {
                            contentTextView.text = "内容加载失败，显示摘要：\n${news.digest ?: "无内容"}"
                        }
                    }
                }.start()
            } catch (e: Exception) {
                Log.e("NewsDetailActivity", "处理新闻内容失败", e)
                contentTextView.text = news.digest ?: "内容加载失败"
            }
            
            // 检查是否收藏
            isFavorite = news.isFavorite
            updateFavoriteButton()
        } catch (e: Exception) {
            Log.e("NewsDetailActivity", "显示新闻详情失败", e)
            showError("显示新闻详情失败")
        }
    }
    
    private fun showLoading() {
        progressBar.visibility = View.VISIBLE
        errorTextView.visibility = View.GONE
    }
    
    private fun hideLoading() {
        progressBar.visibility = View.GONE
    }
    
    private fun showError(message: String) {
        try {
            progressBar.visibility = View.GONE
            errorTextView.visibility = View.VISIBLE
            errorTextView.text = message
            // 使用Handler延迟显示Toast，避免在主线程阻塞
            handler.post {
                Toast.makeText(this@NewsDetailActivity, message, Toast.LENGTH_SHORT).show()
            }
        } catch (e: Exception) {
            Log.e("NewsDetailActivity", "显示错误信息失败", e)
        }
    }
    
    private fun showErrorAndFinish(message: String) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
        finish()
    }
    
    private fun toggleFavorite() {
        try {
            // 通过repository直接切换收藏状态
            try {
                val repository = com.newshub.app.data.repository.NewsRepository
                repository.toggleFavorite(newsId)
                
                // 更新本地状态
                isFavorite = !isFavorite
                
                Log.d("NewsDetailActivity", "收藏状态切换成功: $isFavorite")
                
                // 更新按钮状态
                updateFavoriteButton()

                // 显示提示信息
                val message = if (isFavorite) "已添加到收藏" else "已取消收藏"
                handler.post {
                    Toast.makeText(this@NewsDetailActivity, message, Toast.LENGTH_SHORT).show()
                }
            } catch (e: Exception) {
                Log.e("NewsDetailActivity", "切换收藏失败", e)
                handler.post {
                    Toast.makeText(this@NewsDetailActivity, "操作失败: ${e.message}", Toast.LENGTH_SHORT).show()
                }
            }
        } catch (e: Exception) {
            Log.e("NewsDetailActivity", "切换收藏状态失败", e)
            handler.post {
                Toast.makeText(this@NewsDetailActivity, "操作失败", Toast.LENGTH_SHORT).show()
            }
        }
    }
    
    private fun updateFavoriteButton() {
        try {
            if (isFavorite) {
                // 使用Android系统自带的收藏图标
                favoriteButton.setImageResource(android.R.drawable.star_on)
            } else {
                // 使用Android系统自带的未收藏图标
                favoriteButton.setImageResource(android.R.drawable.star_off)
            }
        } catch (e: Exception) {
            Log.e("NewsDetailActivity", "更新收藏按钮图标失败", e)
        }
    }
}